﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class ChatItem : MonoBehaviour
{

	public Image avatarImage;

	public Text nick;

	public Text lastMsg;

	public Text lastTime;

	public Image unReadImage;

	private Button _button;

	private ChatVO _chatVo;

	public ChatVO ChatVo
	{
		get { return _chatVo; }
		set { _chatVo = value; }
	}

	public void SyncShow()
	{
		//todo 处理image
		nick.text = _chatVo.Nick;
		lastMsg.text = _chatVo.LastMsg;
		lastTime.text = _chatVo.UpdateTime;
		if (_chatVo.Type.Equals("unRead"))
		{
			unReadImage.gameObject.SetActive(true);	
		}else if (_chatVo.Type.Equals("read"))
		{
			unReadImage.gameObject.SetActive(false);	
		}
		HttpTool.Instance.GetImageConvertToSpriteByURL(_chatVo.Avatar,"opponent");
		StartCoroutine(SetSpriteToImage());

	}
	
	// Use this for initialization
	void Start ()
	{
		_button = this.gameObject.GetComponent<Button>();
		
		//点击事件函数绑定
		_button.onClick.AddListener(delegate { StartChat(); });
	}
	
	// Update is called once per frame
	void Update () {
		
	}


	private void StartChat()
	{
		Debug.Log("开始聊天");
		StartChatRequest request = UnityFacade.Instance.UiManager.InstantiatedPanelDict[PanelType.ChatListPanel].GetComponent<StartChatRequest>();
		request.SendRequest(_chatVo.UserId);
	}
	
	
	private IEnumerator SetSpriteToImage()
	{
		//todo 可以开启一个等待动画的显示
        
		while (HttpTool.Instance.OpponentSprite == null)
		{
			yield return new WaitForFixedUpdate();
		}
		avatarImage.sprite = HttpTool.Instance.OpponentSprite;
		//置为null，待下一次处理
		HttpTool.Instance.ClearSprite("opponent");
       
	}
}
